<?php
require_once 'auth.php';
requireLogin();

$conn = dbConnect();

// 获取要编辑的商品数据
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['id'])) {
    $stmt = $conn->prepare('SELECT * FROM inventory WHERE id = ?');
    $stmt->bind_param('i', $_GET['id']);
    $stmt->execute();
    $item = $stmt->get_result()->fetch_assoc();
    
    if (!$item) {
        $_SESSION['error'] = '商品不存在';
        header('Location: inventory.php');
        exit;
    }
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $errors = [];
    
    // 表单验证
    $requiredFields = ['product_name', 'sku', 'quantity', 'location'];
    foreach ($requiredFields as $field) {
        if (empty($_POST[$field])) {
            $errors[] = '必填字段不能为空：' . $field;
        }
    }
    
    if (!filter_var($_POST['quantity'], FILTER_VALIDATE_INT) || $_POST['quantity'] < 0) {
        $errors[] = '库存数量必须为有效数字';
    }
    
    if (empty($errors)) {
        try {
            $conn->autocommit(FALSE);
            
            // 更新库存信息
            $updateStmt = $conn->prepare('UPDATE inventory SET 
                product_name = ?, 
                sku = ?, 
                quantity = ?, 
                location = ?, 
                last_updated = NOW() 
                WHERE id = ?');
            $updateStmt->bind_param('ssisi', 
                $_POST['product_name'],
                $_POST['sku'],
                $_POST['quantity'],
                $_POST['location'],
                $_POST['id']);
            $updateStmt->execute();
            
            // 记录操作日志
            $logStmt = $conn->prepare("INSERT INTO operation_logs 
                (user_id, operation_type, target_id, details) 
                VALUES (?, 'edit', ?, ?)");
            $logDetails = '更新商品信息：' . json_encode($_POST, JSON_UNESCAPED_UNICODE);
            $logStmt->bind_param('iis', $_SESSION['user_id'], $_POST['id'], $logDetails);
            $logStmt->execute();
            
            $conn->commit();
            
            $_SESSION['success'] = '商品更新成功';
            header('Location: inventory.php');
            exit;
            
        } catch (Exception $e) {
            $conn->rollback();
            $errors[] = '更新失败：' . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>编辑商品</title>
    <link rel="stylesheet" href="/dist/css/tabler.min.css">
</head>
<body class="layout-fluid layout-vertical">
    <?php include 'navbar.php'; ?>

    <div class="page">
        <div class="container-fluid">
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">编辑商品</h3>
                            <div class="ms-auto">
                                <!-- 修改为与 inventory_add.php 一致的返回按钮样式 -->
                                <a href="inventory.php" class="btn btn-secondary">返回列表</a>
                            </div>
                        </div>
                        
                        <!-- 修改错误提示框样式 -->
                        <?php if (!empty($errors)): ?>
                            <?php foreach ($errors as $error): ?>
                                <div class="alert alert-danger" role="alert">
                                    <div class="alert-icon">
                                        <!-- Download SVG icon from http://tabler.io/icons/icon/alert-circle -->
                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                                            viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                                            stroke-linecap="round" stroke-linejoin="round"
                                            class="icon alert-icon icon-2">
                                            <path d="M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0" />
                                            <path d="M12 8v4" />
                                            <path d="M12 16h.01" />
                                        </svg>
                                    </div>
                                    <?= htmlspecialchars($error) ?>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>

                        <!-- 添加成功提示框 -->
                        <?php if (isset($_SESSION['success'])): ?>
                            <div class="alert alert-success" role="alert">
                                <div class="alert-icon">
                                    <!-- Download SVG icon from http://tabler.io/icons/icon/check -->
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                                        viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                                        stroke-linecap="round" stroke-linejoin="round"
                                        class="icon alert-icon icon-2">
                                        <path d="M5 12l5 5l10 -10" />
                                    </svg>
                                </div>
                                <div>
                                    <h4 class="alert-heading">Wow! Everything worked!</h4>
                                    <div class="alert-description">
                                        <?= htmlspecialchars($_SESSION['success']) ?>
                                    </div>
                                </div>
                            </div>
                            <?php unset($_SESSION['success']); ?>
                        <?php endif; ?>

                        <form method="post">
                            <input type="hidden" name="id" value="<?= $item['id'] ?? '' ?>">
                            
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label">商品名称</label>
                                    <input type="text" class="form-control" name="product_name" 
                                        value="<?= htmlspecialchars($item['product_name'] ?? '') ?>">
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">SKU编码</label>
                                            <input type="text" class="form-control" name="sku" 
                                                value="<?= htmlspecialchars($item['sku'] ?? '') ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">当前库存</label>
                                            <input type="number" class="form-control" name="quantity"
                                                min="0" step="1" 
                                                value="<?= htmlspecialchars($item['quantity'] ?? 0) ?>">
                                        </div>
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">存放位置</label>
                                    <input type="text" class="form-control" name="location" 
                                        value="<?= htmlspecialchars($item['location'] ?? '') ?>">
                                </div>
                            </div>

                            <div class="card-footer text-end">
                                <button type="submit" class="btn btn-primary">保存修改</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="/dist/js/tabler.min.js"></script>
</body>
</html>